package threadedserver;

import java.awt.*;
import java.io.*;
import java.net.*;
import java.awt.event.*;
import java.util.*;

public class ThreadServerSolution extends Frame implements ActionListener, Runnable {

    private Button quitButton;
    private TextArea messages;

//Code which just sets up the visual objects, can be ignored
    public ThreadServerSolution(String title) {
        super(title);
        this.setLayout(new FlowLayout());
        add(quitButton = new Button("Quit"));
        add(messages = new TextArea(10, 40));
        quitButton.addActionListener(this);
        this.setSize(300, 300);
        this.setVisible(true);
    }

    //Code which processes button events can be ignored
    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource() == quitButton) {
            try {
                messages.append("...Quitting");
                Thread.sleep(2000);
            } catch (Exception e) {
            }
            System.exit(0);
        }
    }

    //Code which runs the server, do not ignore
    public void run() {
        try {
            System.out.print("Student solution executing***");
            //Set up server socket
            messages.append("...Server started\n");
            ServerSocket ss = new ServerSocket(2001);
            messages.append("...Socket obtained\n");
            Thread connThread;
            int count = 0;
            //Loop around waiting for connections, when one comes in
            //create a new thread to handle it
            while (true) {
                //Create a socket from the server socket ss
                //increment count by one and start a new ConnectionThread thread
                Socket s = ss.accept();
                count++;
                (new ConnectionThread(s, messages, count)).start();
            }
        } catch (Exception e) {
            System.out.println("Problem starting server" + e);
        }
    }
}